package com.insigma.business.qrcode.soldier._provider.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayOpenPublicMessageSingleSendRequest;
import com.alipay.api.response.AlipayOpenPublicMessageSingleSendResponse;
import com.google.common.collect.Maps;

import com.insigma.business.qrcode.common.util.ResponseUtils;
import com.insigma.business.qrcode.common.vo.BaseResponse;
import com.insigma.business.qrcode.soldier.dto.AliSshTemplate;
import com.insigma.business.qrcode.soldier.entity.SoldierBasicInfoDO;
import com.insigma.business.qrcode.soldier.entity.SoldierOuterLoginAccountDO;
import com.insigma.business.qrcode.soldier._provider.AliShhProvider;
import com.insigma.business.qrcode.soldier.service.SoldierBasicInfoService;
import com.insigma.business.qrcode.soldier.service.SoldierOuterLoginAccountService;
import com.insigma.business.qrcode.soldier.service.impl.AliPayClientFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;


@Slf4j
@Service
@Component("aliShhProvider")
public class AliShhProviderImpl implements AliShhProvider {
    @Autowired
    private AliPayClientFactory aliPayClientFactory;

    @Value("${ali.template.qr.approve.template.id}")
    private String qrApproveTemplateId;

    @Value("${ali.template.qr.approve.url}")
    private String qrApproveUrl;

    @Value("${ali.template.remind.template.id}")
    private String remindTemplateId;

    @Value("${ali.template.activity.url}")
    private String activityUrl;

    @Autowired
    private SoldierOuterLoginAccountService soldierOuterLoginAccountService;

    @Autowired
    private SoldierBasicInfoService soldierBasicInfoService;

    @Override
    public BaseResponse<Boolean> sendTemplateMsg(AliSshTemplate body) {
        AlipayClient alipayClient = aliPayClientFactory.getInstance();
        AlipayOpenPublicMessageSingleSendRequest request = new AlipayOpenPublicMessageSingleSendRequest();
        request.setBizContent(JSON.toJSONString(body));
        AlipayOpenPublicMessageSingleSendResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if (response.isSuccess()) {
            log.info("调用成功");
            return ResponseUtils.buildSuccessResponse(true);
        } else {
            log.error("调用失败:{}", response);
            return ResponseUtils.buildSuccessResponse(false);
        }
    }

    @Override
    public BaseResponse<Boolean> sendQrApproveResult(String outerUserId, Boolean result, String msg) {
        Map<String, String> contentMap = Maps.newHashMap();
        String checkResultMsg = result ? "成功" : "失败";
        contentMap.put("first", "您的老兵码申请审核" + checkResultMsg + "。");
        contentMap.put("keyword1", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        contentMap.put("keyword2", msg);
        contentMap.put("remark", msg);
        AliSshTemplate body = new AliSshTemplate(qrApproveTemplateId, outerUserId, qrApproveUrl, contentMap);
        return sendTemplateMsg(body);
    }

    @Override
    public BaseResponse<Boolean> sendActivityRemind(String soldierId, String msg) {
        SoldierOuterLoginAccountDO accountDtoBySoldierId = soldierOuterLoginAccountService.getAccountDtoBySoldierId(soldierId);
        String outerUserId = accountDtoBySoldierId.getOuterSysAccountId();
        log.info("发送活动提醒，{}， {}", outerUserId, msg);
        Map<String, String> contentMap = Maps.newHashMap();
        contentMap.put("keyword1", "码上活动");
        contentMap.put("keyword2", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        contentMap.put("remark", msg);
        AliSshTemplate body = new AliSshTemplate(remindTemplateId, outerUserId, activityUrl, contentMap);

        return sendTemplateMsg(body);
    }

    @Override
    public BaseResponse<Boolean> sendActivityJx(List<String> idCardList,String title, String msg) {
        for (String idCard : idCardList) {
            SoldierBasicInfoDO byIdCardNo = soldierBasicInfoService.getByIdCardNo(idCard);
            System.out.println(byIdCardNo);
            SoldierOuterLoginAccountDO accountDtoBySoldierId = null;
            if(byIdCardNo != null && byIdCardNo.getSoldierId() != null){
                 accountDtoBySoldierId = soldierOuterLoginAccountService.getAccountDtoBySoldierId(byIdCardNo.getSoldierId());
            }
            if(accountDtoBySoldierId != null){
                String outerUserId = accountDtoBySoldierId.getOuterSysAccountId();
                log.info("发送课程提醒，{}， {}", outerUserId, msg);
                Map<String, String> contentMap = Maps.newHashMap();
                contentMap.put("first", "新活动：" + title + "。");
                contentMap.put("keyword1", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                contentMap.put("keyword2", msg);
                contentMap.put("remark", msg);
                AliSshTemplate body = new AliSshTemplate(qrApproveTemplateId, outerUserId, null, contentMap);
                sendTemplateMsg(body);
            }
        }
        return ResponseUtils.buildSuccessResponse(true);
    }


    public static void main(String[] args) {
        String body = "{\n" +
        "    \"to_user_id\":\"2088512144656451\",\n" +
                "    \"template\":{\n" +
                "        \"template_id\":\"b093e67a659845ff95f61df72ac2de2b\",\n" +
                "        \"context\":{\n" +
                "            \"head_color\":\"#85be53\",\n" +
                "            \"url\":\"http://m.baidu.com\",\n" +
                "            \"action_name\":\"查看详情\",\n" +
                "            \"keyword1\":{\n" +
                "                \"color\":\"#85be53\",\n" +
                "                \"value\":\"时间\"\n" +
                "            },\n" +
                "            \"keyword2\":{\n" +
                "                \"color\":\"#85be53\",\n" +
                "                \"value\":\"内容\"\n" +
                "            },\n" +
                "            \"first\":{\n" +
                "                \"color\":\"#85be53\",\n" +
                "                \"value\":\"first\"\n" +
                "            },\n" +
                "            \"remark\":{\n" +
                "                \"color\":\"#85be53\",\n" +
                "                \"value\":\"马克\"\n" +
                "            }\n" +
                "        }\n" +
                "    }\n" +
                "}";
        System.out.println(body);
    }
}
